<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form ref="searchForm" :inline="true" :model="queryData">
				<el-form-item
					:label="`${$t('system.currency')}:`"
					prop="currency"
				>
					<el-select
						v-model="queryData.currency"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
						style="width: 220px"
					>
						<el-option
							v-for="item in currencySymbol"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item style="margin-left: 8px">
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="loadData"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('906021')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="addLabel"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				:header-cell-style="getRowClass"
				highlight-current-row
				:max-height="tableHeight"
			>
				<el-table-column
					prop="bankName"
					align="center"
					:label="$t('common.components.card_name')"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.bankName || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="bankLogo"
					align="center"
					:label="$t('common.bank_logo')"
				>
					<template slot-scope="scope">
						<span v-if="scope.row.bankLogo === null">-</span>
						<span
							v-else
							class="text-link"
							@click="
								imageAddress = scope.row.bankLogo
								imageViewerVisible = true
							"
						>
							{{ $t('common.click_show') }}
						</span>
					</template>
				</el-table-column>

				<el-table-column
					prop="currency"
					align="center"
					:label="
						$t('funds.thirdPeymentChannelConfig.support_currency')
					"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.currency || '-' }}</span>
					</template>
				</el-table-column>

				<!-- <el-table-column
						prop="status"
						align="center"
						:label="$t('common.status')"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.status + '' === '0'" class="disableRgba">
								{{ $t('common.status_disabled') }}
								{{ typeFilter(scope.row.pageStatus, 'operateStatus') }}
							</span>
							<span v-else-if="!!scope.row.status" class="normalRgba">
								{{ typeFilter(scope.row.pageStatus, 'operateStatus') }}
								{{ $t('common.status_turn_on') }}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column> -->
				<el-table-column
					prop="createdBy"
					align="center"
					:label="$t('common.createBy')"
					width="120"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdBy || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="$t('common.createAt')"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdAt || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedBy"
					align="center"
					:label="$t('common.last_updateBy')"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.updatedBy || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedAt"
					align="center"
					:label="$t('common.last_updateAt')"
				>
					<template slot-scope="scope">
						<span>{{ scope.row.updatedAt || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="pageStatus"
					align="center"
					:label="$t('common.actions')"
					width="300"
				>
					<template slot-scope="scope">
						<!-- <el-button
								v-if="scope.row.status && hasPermission('906023')"
								type="danger"
								size="medium"
								@click="recycle(scope.row)"
							>
								{{ $t('common.disabled') }}
							</el-button>
							<el-button
								v-if="!scope.row.status && hasPermission('906023')"
								type="success"
								size="medium"
								@click="recycle(scope.row)"
							>
								{{ $t('common.start_up') }}
							</el-button> -->
						<el-button
							v-if="hasPermission('906022')"
							type="primary"
							icon="el-icon-edit"
							:disabled="scope.row.pageStatus === 1"
							size="medium"
							@click="edit(scope.row)"
						>
							{{ $t('common.edit') }}
						</el-button>
						<!-- <el-button
								v-if="hasPermission('906024')"
								type="danger"
								icon="el-icon-delete"
								size="medium"
								:disabled="scope.row.pageStatus === 1"
								@click="deleteLabel(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button> -->
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				:total="total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			center
			:title="title"
			:visible.sync="dialogFormVisible"
			:destroy-on-close="true"
			:width="getWidth('520px', 1.8)"
			class="rempadding"
			@close="clear"
		>
			<el-divider></el-divider>
			<el-form
				ref="formSub"
				:model="dialogForm"
				label-width="100px"
				:rules="rules"
			>
				<el-form-item
					:label="`${$t('common.components.card_name')}:`"
					prop="bankName"
				>
					<el-input
						v-model="dialogForm.bankName"
						v-symbols
						:maxlength="20"
						autocomplete="off"
						style="width: 330px"
						:placeholder="$t('common.please_enter')"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="
						`${$t(
							'funds.thirdPeymentChannelConfig.support_currency'
						)}:`
					"
					prop="currency"
				>
					<el-select
						v-model="dialogForm.currency"
						size="medium"
						:placeholder="$t('common.please_choose')"
						clearable
						style="width: 330px"
					>
						<el-option
							v-for="item in currencySymbol"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="$t('common.bank_logo')"
					class="upload-item-form"
				>
					<UploadItem
						ref="imgUpload"
						:upload-file-type="'image'"
						:platform="'PC'"
						:uploadAPI="uploadAPI"
						:img-url="dialogForm.bankLogo"
						:bounds="imageSize"
						:fileSize="fileSize"
						@upoladItemSucess="handleUploadSucess"
						@startUpoladItem="handleStartUpload"
						@deleteUpoladItem="handleDeleteUpload"
						@upoladItemDefeat="handleUploadDefeat"
					></UploadItem>
				</el-form-item>
				<div class="upload-item-form-tip">
					<span class="upload-item-form-start">*</span>
					{{ $t('operation.upload_tips1') }}png，jpg *

					{{ $t('operation.upload_tips3') }}5M
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
		<!-- <image-viewer
				v-if="rowData"
				:visible.sync="imageViewerVisible"
				:url-list="[imageAddress]"
			/> -->
		<el-dialog
			v-if="rowData"
			:visible.sync="imageViewerVisible"
			:title="`${$t('common.bank_logo')}预览`"
			:width="getWidth('700px')"
		>
			<div v-if="imageAddress" class="img-view">
				<div v-show="imageAddress">
					<el-image :src="imageAddress" lazy></el-image>
				</div>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import { mapGetters } from 'vuex'
import MainContent from '@/components/MainContent/index.vue'
// import UploadItem from './components/uploadItem'
// import { isHaveEmoji, notSpecial2 } from '@/utils/validate'
import {
	bankManageQuery,
	setBankManageAdd,
	setBankManageUpdate,
	setBankManageUpdateBankStatus
} from '@/api/secret'

export default {
	name: routerNames.bankManagement,
	components: {
		UploadItem: () => import('@/components/UploadItem'),
		MainContent
	},
	mixins: [list],
	data() {
		this.deleteLabel = this.throttle(this.deleteLabel, 1000)
		this.subAddOrEdit = this.throttle(this.subAddOrEdit, 1000)
		this.recycle = this.throttle(this.recycle, 1000)
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			imageAddress: '',
			rowData: {},
			searchAdminType: 0,
			queryData: {
				pageName: undefined,
				pageStatus: undefined,
				createdBy: undefined,
				updatedBy: undefined,
				merchantClientId: ''
			},
			tableData: [],
			dialogFormVisible: false,
			dialogForm: {
				bankName: undefined,
				bankLogo: '',
				currency: undefined
			},
			total: 0,
			title: '',
			bankLogo: null,
			imageViewerVisible: false
		}
	},
	computed: {
		...mapGetters(['merchantInfo']),
		currencySymbol() {
			return this.globalDics.currencySymbol || []
		},
		rules() {
			const bankName = [
				{
					required: true,
					message: '请输入银行名称',
					trigger: 'blur'
				}
			]
			const currency = [
				{
					required: true,
					message: '请选择支持币种',
					trigger: 'change'
				}
			]
			const bankLogo = [
				{
					required: true,
					message: this.$t('common.please_upload_img'),
					trigger: 'change'
				}
			]
			return {
				bankName,
				currency,
				bankLogo
			}
		},
		imageSize() {
			return {
				width: 1125,
				height: 2436
			}
		},
		fileSize() {
			return 5 * 1024 * 1024
		},
		uploadAPI() {
			return this.$api.imageUploadAPI
		}
	},
	mounted() {
		if (!this.$store.getters.isZk) {
			this.queryData.merchantClientId = this.$store.getters.merchantInfo.id
			this.loadData()
		}
	},
	methods: {
		loadData() {
			this.loading = true
			const params = {
				...this.queryData,
				...this.getParams()
			}
			for (const k in params) {
				if (params[k] === '' || params[k] === undefined) {
					delete params[k]
				}
			}

			bankManageQuery(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						const { record, totalRecord } = res.data || {}
						this.tableData = Array.isArray(record)
							? Object.freeze(record)
							: []
						this.total = totalRecord || 0
					} else {
						this.$message({
							message: res?.msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					this.loading = false
				})

			setTimeout(() => {
				this.loading = false
			}, 1000)
		},
		reset() {
			this.pageNum = 1
			this.$refs.searchForm.resetFields()
			if (!this.$store.getters.isZk) {
				this.queryData.merchantClientId = this.$store.getters.merchantInfo.id
			}
			this.loadData()
		},
		addLabel() {
			this.dialogForm.bankLogo = ''
			this.dialogFormVisible = true
			this.$nextTick(() => {
				this.$refs.formSub.clearValidate()
			})
			this.$refs.imgUpload?.clearFile?.()

			this.title = this.$t('common.add')
			this.dialogForm = {}
		},
		edit(val) {
			this.rowData = val
			this.dialogForm = { ...val }
			this.title = this.$t('common.edit')
			for (const k in this.dialogForm) {
				this.dialogForm[k] = val[k]
			}

			this.$nextTick(() => {
				this.$refs.imgUpload.state = 'image'
				if (val.bankLogo) {
					this.$refs.imgUpload.fileUrl = val.bankLogo
				} else {
					this.$refs.imgUpload.fileUrl = undefined
					this.$refs.imgUpload?.clearFile?.()
				}
			})

			this.dialogForm.merchantClientId = val.merchantId
			this.dialogFormVisible = true
		},
		deleteLabel(val) {
			const { id } = val
			this.$confirm(
				`<strong>${this.$t('common.delete_tips')}?</strong>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					this.$api
						.setBankManageelete({ id })
						.then((res) => {
							loading.close()
							if (res?.code === 200) {
								this.$message.success(
									this.$t('common.delete_success')
								)
							} else {
								this.$message({
									type: 'error',
									message: this.$t('common.delete_fail')
								})
							}

							this.loadData()
						})
						.catch(() => {
							loading.close()
						})
					setTimeout(() => {
						loading.close()
					}, 1000)
				})
				.catch(() => {})
		},
		subAddOrEdit() {
			const params = {
				...this.dialogForm
			}
			const sub =
				this.title !== this.$t('common.edit')
					? setBankManageAdd
					: setBankManageUpdate
			if (this.title === this.$t('common.edit')) {
				params.id = this.rowData.id
			}
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					sub(params).then((res) => {
						if (res?.code === 200) {
							const message =
								this.title !== this.$t('common.edit')
									? this.$t('common.add_success')
									: this.$t('common.edit_success')
							this.$message({
								message,
								type: 'success'
							})
						} else {
							this.$message({
								message: res?.msg,
								type: 'error'
							})
						}
					})
					this.dialogFormVisible = false
					setTimeout(() => {
						this.loadData()
					}, 1000)
				}
			})
		},
		checkValue(e) {
			// const { value } = e.target
		},
		clear() {
			this.$refs.formSub.resetFields()
		},
		preViewPicture(val) {
			const { bankLogo } = val
			this.bankLogo = bankLogo
			this.dialogPictureVisible = true
		},
		// 状态修改
		recycle(val) {
			const { id } = val
			const status = val.status === 0 ? 1 : 0
			this.$confirm(
				`<strong>${this.$t(
					'operation.switch_status_tips3'
				)}</strong></br>
                 <span style='font-size:12px;color:#c1c1c1'>${this.$t(
						'operation.switch_status_tips2'
					)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					setBankManageUpdateBankStatus({
						id,
						status
					}).then((res) => {
						if (res?.code === 200) {
							this.$message({
								message: this.$t('common.action_success'),
								type: 'success'
							})
						} else {
							this.$message({
								message: res?.msg,
								type: 'error'
							})
						}
						this.loadData()
					})
				})
				.catch(() => {})
		},
		handleStartUpload() {
			this.$message.info(this.$t('common.upload_start'))
		},
		handleUploadSucess({ index, file, id }) {
			this.dialogForm.bankLogo = file.imgUrl
		},
		handleUploadDefeat() {
			this.dialogForm.bankLogo = ''
			this.$message.error(this.$t('common.upload_fail'))
		},
		handleDeleteUpload() {
			this.dialogForm.bankLogo = ''
			this.$message.warning(this.$t('common.upload_del'))
		}
	}
}
</script>

<style lang="scss" scoped>
.upload-item-form {
	::v-deep .el-form-item__content {
		margin-top: 4px;
		display: flex;
		align-items: center;
		row-gap: 16px;
	}
}

.upload-item-form-start {
	color: #f56c6c;
}

.upload-item-form-tip {
	margin-left: 16px;
	line-height: 1;
	width: 320px;
	line-height: 20px;
}
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .tagheight .el-tag {
	height: 24px;
	line-height: 24px;
	min-width: 60px;
}
::v-deep .rempadding .el-dialog__body {
	padding: 0;
	padding-bottom: 30px;

	.contentBox,
	form {
		padding: 0 20px;
	}
}
::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}
::v-deep .el-input-number--medium .el-input__inner {
	padding: 0 15px;
	text-align: left;
}

.decoration {
	text-decoration: underline;
	cursor: pointer;
}
.bodyBox {
	max-height: 400px;
	overflow: auto;
}
p {
	display: flex;
	height: 40px;
	line-height: 40px;
	border-bottom: 1px solid #e8e8e8;
	justify-content: space-around;
	span {
		display: inline-block;
		width: 50%;
		text-align: center;
	}
}
.headerBox {
	color: #000000d8;
	background: #fafafa;
	font-family: 'PingFang SC ', 'PingFang SC', sans-serif;
	font-weight: 650;
	border-top: 1px solid #e8e8e8;
	margin-top: 15px;
}
.img-view {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	div {
		margin: 0 0 20px 0;
		width: 350px;
		img {
			width: 100%;
			height: auto;
			display: block;
		}
	}
}
</style>
